package com.alibaba.datax.core.statistics.container.communicator;


import com.alibaba.datax.common.statistics.VMInfo;
import com.alibaba.datax.common.util.Configuration;
import com.alibaba.datax.core.statistics.communication.Communication;
import com.alibaba.datax.core.statistics.container.collector.AbstractCollector;
import com.alibaba.datax.core.statistics.container.report.AbstractReporter;
import com.alibaba.datax.core.util.container.CoreConstant;
import com.alibaba.datax.dataxservice.face.domain.enums.State;

import java.util.List;
import java.util.Map;

/**
 * 抽象类 容器通信器，
 * 处理JobContainer、TaskGroupContainer和Task的通讯
 */
public abstract class AbstractContainerCommunicator {


  private Configuration configuration;

  /**
   * Collector负责管理下级注册到上级，搜集并合并下级所有的信息
   */
  private AbstractCollector collector;

  private AbstractReporter reporter;

  private Long jobId;

  private VMInfo vmInfo = VMInfo.getVmInfo();

  private long lastReportTime = System.currentTimeMillis();


  public Configuration getConfiguration() {
    return this.configuration;
  }

  public AbstractCollector getCollector() {
    return collector;
  }

  public AbstractReporter getReporter() {
    return reporter;
  }

  public void setCollector(AbstractCollector collector) {
    this.collector = collector;
  }

  public void setReporter(AbstractReporter reporter) {
    this.reporter = reporter;
  }

  public Long getJobId() {
    return jobId;
  }

  public AbstractContainerCommunicator(Configuration configuration) {
    this.configuration = configuration;
    this.jobId = configuration.getLong(CoreConstant.DATAX_CORE_CONTAINER_JOB_ID);
  }


  public abstract void registerCommunication(List<Configuration> configurationList);

  public abstract Communication collect();

  public abstract void report(Communication communication);

  public abstract State collectState();

  public abstract Communication getCommunication(Integer id);


  /**
   * 当 实现是 TGContainerCommunicator 时，返回的 Map: key=taskId, value=Communication <br/>
   * 当 实现是 JobContainerCommunicator 时，返回的 Map: key=taskGroupId, value=Communication
   *
   * @return Map<Integer, Communication>
   */
  public abstract Map<Integer, Communication> getCommunicationMap();

  public void resetCommunication(Integer id) {
    Map<Integer, Communication> map = getCommunicationMap();
    map.put(id, new Communication());
  }

  /**
   * 将vm信息 每5分钟打印一次
   */
  public void reportVmInfo() {
    int printIntervalTime = 5 * 60 * 1000;
    long now = System.currentTimeMillis();
    //每5分钟打印一次
    if (now - lastReportTime >= printIntervalTime) {
      //当前仅打印
      if (vmInfo != null) {
        vmInfo.getDelta(true);
      }
      lastReportTime = now;
    }
  }
}